package com.zhuangjie.mvc.handler.mybatis_type_handler;

import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * List<String>{1,2,3} <-> String（"1,2,3"）
 */
public class WeekTypeHandler extends BaseTypeHandler<List<String>> {

    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, List<String> parameter, JdbcType jdbcType)
            throws SQLException {
        ps.setString(i, parameter.stream().map(String::toString).collect(Collectors.joining(",")));
    }

    private List<String> convertJsonString(String str) {
        if (str == null) return null;
        return Arrays.stream(str.split(","))
                .map(String::valueOf)
                .collect(Collectors.toList());

    }

    @Override
    public List<String> getNullableResult(ResultSet rs, String columnName) throws SQLException {
        return convertJsonString(rs.getString(columnName));
    }

    @Override
    public List<String> getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        return convertJsonString(rs.getString(columnIndex));
    }

    @Override
    public List<String> getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        return convertJsonString(cs.getString(columnIndex));
    }


}
